<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <!-- 循环渲染此处 -->
              <el-option v-for="item in cateList" :key="item.id" :label="item.cate_name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px;">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="initArtList">筛选</el-button>
            <el-button type="info" size="small" @click="resetList">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button type="primary" size="small" class="btn-pub" @click="pubDialogVisible = true">发表文章</el-button>
      </div>

      <!-- 文章表格区域 -->
      <el-table :data="artList" style="width: 100%;" border stripe>
        <el-table-column label="文章标题" prop="title">
          <template v-slot="{ row }">
             <el-link type="primary" @click="showDetail(row.id)">{{ row.title }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="分类" prop="cate_name"></el-table-column>
        <el-table-column label="发表时间">
          <template v-slot="{ row }">
            {{ row.pub_date | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="state"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button type="danger" size="mini" @click="remove(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="q.pagenum"
        :page-sizes="[2, 3, 5, 10]"
        :page-size="q.pagesize"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>

    </el-card>


    <!-- 发表文章的 Dialog 对话框 @open调用初始化文章 -->
    <el-dialog @closed="onDialogClosed" @open="initCateList" title="发表文章" :visible.sync="pubDialogVisible" fullscreen :before-close="handleClose">

      <!-- 发布文章的对话框 -->
      <el-form :model="pubForm" :rules="pubFormRules" ref="pubFormRef" label-width="100px">

        <el-form-item label="文章标题" prop="title">
          <el-input v-model="pubForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>

        <el-form-item label="文章分类" prop="cate_id">
          <el-select v-model="pubForm.cate_id" placeholder="请选择分类" style="width: 100%;">
            <!-- 遍历此处 -->
            <el-option v-for="item in cateList" :label="item.cate_name" :value="item.id" :key="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="文章内容" prop="content">
          <!-- 使用 v-model 进行双向的数据绑定 -->
          <quill-editor @blur="onEditorChange()" v-model="pubForm.content"></quill-editor>
        </el-form-item>

        <el-form-item label="文章封面">
          <!-- 用来显示封面的图片 -->
          <img src="../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef" />
          <br />
          <!-- 文件选择框，默认被隐藏 -->
          <input type="file" style="display: none;" accept="image/*" ref="iptFile" @change="onCoverChange" />
          <!-- 选择封面的按钮 -->
          <el-button type="text" @click="chooseImg">+ 选择封面</el-button>
        </el-form-item>

        <el-form-item label="">
        <el-button type="primary" @click="pubArticle('已发布')">发布</el-button>
        <el-button type="info" @click="pubArticle('草稿')">存为草稿</el-button>
        </el-form-item>

      </el-form>

    </el-dialog>

    <!-- 查看文章详情的对话框 -->
    <el-dialog title="文章预览" :visible.sync="detailVisible" width="80%">

      <!-- 查看文章详情的对话框 -->
      <el-dialog title="文章预览" :visible.sync="detailVisible" width="80%">
        <h1 class="title">{{ artDetail.title }}</h1>

        <div class="info">
          <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
          <span>发布时间：{{ artDetail.pub_date | dateFormat }}</span>
          <span>所属分类：{{ artDetail.cate_name }}</span>
          <span>状态：{{ artDetail.state }}</span>
        </div>
        
        <!-- 分割线 -->
        <el-divider></el-divider>

        <img :src="'http://www.liulongbin.top:3008' + artDetail.cover_img" alt="" />

        <div v-html="artDetail.content"></div>
      </el-dialog>
    </el-dialog>

  </div>

  
</template>

<script>
import defaultImg from "../../assets/images/cover.jpg"

export default {
  name: 'ArtList',
  data() {
    return {
      // 查询参数对象搜索区域的
      q: {
        pagenum: 1,  // 当前页码
        pagesize: 2,  // 每页条数
        cate_id: '',  // 分类id
        state: ''  // 文章状态
      },
      pubDialogVisible: false,
      // 表单的数据对象
      pubForm: {
        title: '',  // 文章标题
        cate_id: '',  // 所属分类的id
        content: '',  // 富文本的内容
        cover_img: null,  // 用户选择的封面图片
        state: ''
      },
      // 表单的验证规则对象
      pubFormRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 30, message: '文章标题的长度为1-30个字符', trigger: 'blur' }
        ],
        cate_id: [{ required: true, message: '请选择文章分类', trigger: 'blur' }],
        content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }],
      },
      cateList: [],  // 返回的文章分类数据
       // 文章的列表数据
      artList: [],
      // 总数据条数
      total: 0,
      // 控制文章详情对话框的显示与隐藏
      detailVisible: false,
      // 文章详情信息对象
      artDetail: {}

      
    }
  },
  created() {
    this.initArtList()
    this.initCateList()
  },
  methods: {
    async handleClose(done) {
      // 询问用户是否确认关闭对话框 element
      const confirmResult = await this.$confirm('此操作将导致文章信息丢失, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)  // 实例对象后直接.then(data => data)和.catch(err => {err})
      // 取消关闭
      if (confirmResult === 'cancel') return
      // 确认关闭
      done(true)
    },
    async initCateList() {
      // 初始化文章分类数据
      const { data: res } = await this.$http.get('/my/cate/list')
      if(res.code === 0) {
        this.cateList = res.data
      }
    },
    chooseImg() {
      this.$refs.iptFile.click()
    },
    onEditorChange () {
      this.$refs.pubFormRef.validateField('content')
    },
    onCoverChange(e) {
      const files = e.target.files
      if(files.length > 0) {
        this.pubForm.cover_img = files[0]
        const url = URL.createObjectURL(files[0])
        this.$refs.imgRef.setAttribute('src', url)
      } else {
        this.pubForm.cover_img = null
        this.$refs.imgRef.setAttribute('src', defaultImg)
      }

    },
    pubArticle(state) {
      this.pubForm.state = state
      this.$refs.pubFormRef.validate(valid => {
        if(!valid) return this.$message.error('请选择完善文章信息!')
        if(!this.pubForm.cover_img) return this.$message.error('请选择文章封面!')
        this.postArticle()
      })
    },
    onDialogClosed() {
    this.$refs.pubFormRef.resetFields()
    this.pubForm.content = ''
    this.pubForm.cover_img = null
    this.pubForm.state = ''
    this.$refs.imgRef.setAttribute('src', defaultImg)
    },
    async postArticle() {
      // 1.创建FormDate对象
      const fd = new FormData()
      // 2.向FormData中添加数据
      for (const key in this.pubForm) {
        fd.append(key, this.pubForm[key])
      }
      // 3.使用接口 
      const {data: res} = await this.$http.post('/my/article/add', fd) 
      if(res.code !== 0) return this.$message.error('发布文章失败!')
      this.$message.success('发布文章成功!')
      // 4.关闭对话框 
      this.pubDialogVisible = false
      // 5.刷新文章列表数据
      this.initArtList()
      // 6.重置file类型的input
      this.$refs.iptFile.value = null
    },
    async initArtList() {
      const { data: res } = await this.$http.get('/my/article/list', {params: this.q})
      if(res.code !==0) return this.$message.error('获取文章列表失败!')
      this.artList = res.data
      this.total = res.total
    },
    handleSizeChange(newSIze) {
      this.q.pagesize = newSIze
      this.initArtList()
    },
    handleCurrentChange(newPage) {
      this.q.pagenum = newPage
      // 重新发起请求
      this.initArtList()
    },
    resetList() {  // 点击重置按钮时
      // 1.重置查询参数对象
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      }
      // 2.重新发起请求
      this.initArtList()
    },
    // 展示文章详情
    async showDetail(id) {
      const { data: res } = await this.$http.get('/my/article/info', { params: {id} })
      if(res.code !== 0) return this.$message.error('获取文章详情失败!')
      this.artDetail = res.data
      this.detailVisible = true
    },
    // 根据id删除文章
    async remove(id) {
      // 1.询问框 
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err) 
      // 2.取消了删除
      if(confirmResult === "cancel") return
      // 3.点击了确定
      const { data: res } = await this.$http.delete('/my/article/info', { params: {id} })
      if(res.code !==0) return this.$message.error('删除文章失败!')
      this.$message.success('删除文章成功!')

      // 在 刷新数据之前,当前页的数据只有1条,且当前的页码大于1,
      // 说明当前页已经没有数据要可显示,需要让页码值-1
      if(this.artList.length === 1 && this.q.pagenum > 1) {
        this.q.pagenum--
      }
      // 刷新列表数据
      this.initArtList()

    },

    async remove(id) {
      // 1.询问框 
      try {
        await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      // .catch(err => err) 
      // 2.取消了删除
      // if(confirmResult === "cancel") return
      // 3.点击了确定
      const { data: res } = await this.$http.delete('/my/article/info', { params: {id} })
      if(res.code !==0) return this.$message.error('删除文章失败!')
      this.$message.success('删除文章成功!')

      // 在 刷新数据之前,当前页的数据只有1条,且当前的页码大于1,
      // 说明当前页已经没有数据要可显示,需要让页码值-1
      if(this.artList.length === 1 && this.q.pagenum > 1) {
        this.q.pagenum--
      }
      // 刷新列表数据
      this.initArtList()
      } catch (e) {
        if(e === 'cancel') {
        console.log(e);
        } else {
          this.$message.error('删除文章失败!')
        }

      }
    }


  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
  
}
/deep/ .ql-editor {
  min-height: 300px;
}

.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}

.el-pagination {
  margin-top: 15px;
}

.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}
</style>
